package com.example.pre.tools;

import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 修改版 AES对称加密工具
 * 
 * @ClassName: AESUtil.java
 * @Description: 描述
 */
public class AESUtil {
	/**
	 * 默认密匙
	 */
	public static final String DEFAULT_KEY = "aosatech.service";

	/**
	 * 加密
	 * 
	 * @param privateKey 私匙
	 * @param content    待加密内容
	 */
	public static String encode(String privateKey, String content) {
		try {
			if (privateKey == null || "".equals(privateKey)) {
				privateKey = DEFAULT_KEY;
			}
			KeyGenerator keygen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(privateKey.getBytes());
			keygen.init(128, secureRandom);
			SecretKey original_key = keygen.generateKey();
			byte[] raw = original_key.getEncoded();
			SecretKey key = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] byte_encode = content.getBytes("utf-8");
			byte[] byte_AES = cipher.doFinal(byte_encode);
			String code = new String(Base64.getEncoder().encode(byte_AES));
			// 混淆密码
			code = code.replaceAll("\\+", "a0sAJ").replaceAll("=", "0aASd").replaceAll("/", "AoSaX");
			return code;
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 如果有错就返加nulll
		return null;
	}

	/**
	 * 加密
	 * 
	 * @param content 需要加密的内容
	 * @return
	 */
	public static String encode(String content) {
		return encode(DEFAULT_KEY, content);
	}

	/**
	 * 解密
	 * 
	 * @param privateKey 私匙
	 * @param content    带解密内容
	 */
	public static String decode(String privateKey, String content) {
		try {
			if (privateKey == null || "".equals(privateKey)) {
				privateKey = DEFAULT_KEY;
			}
			// 开始解密，现将混淆的密码还原
			content = content.replaceAll("a0sAJ", "+").replaceAll("0aASd", "=").replaceAll("AoSaX", "/");
			KeyGenerator keygen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(privateKey.getBytes());
			keygen.init(128, secureRandom);
			SecretKey original_key = keygen.generateKey();
			byte[] raw = original_key.getEncoded();
			SecretKey key = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] byte_content = Base64.getDecoder().decode(content);
			byte[] byte_decode = cipher.doFinal(byte_content);
			return new String(byte_decode, "utf-8");
		} catch (Exception e) {
//			e.printStackTrace();
		}
		// 如果有错就返加null
		return null;
	}

	public static String decode(String content) {
		return decode(DEFAULT_KEY, content);
	}
}
